<!doctype html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
<title>Document25</title>

<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet"
      crossorigin="anonymous"/>
</head>

<body>
<div class="container">
    <h2 class="page-header">async和await使用ajax</h2>
    <button class="btn btn-primary" id="btn">点击发送 AJAX</button>
</div>

<script>
    /*
     封装一个函数 sendAjax 发送 GET AJAX 请求
     参数 url
     返回结果 Promise
     */
    function sendAjax(url){
        return new Promise((resolve, reject)=> {
            //4.创建ajax实例对象
            const xhr = new XMLHttpRequest();
            // xhr.responseType = 'json';
            //5.打开请求
            xhr.open('get', url);
            //6.发送请求
            xhr.send();
            //7.利用onreadystatechange事件
            xhr.onreadystatechange = function () {
                //8.判断
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve("success: " + xhr.response);
                    } else {
                        reject(xhr.status);
                    }
                }
            }
        });
    }

    const url = "https://api.apiopen.top/api/getTime";
    var btn = document.querySelector('.btn');
    btn.addEventListener('click', async function(){
        let result = await sendAjax(url);
        console.log("result: "+result)
    })

</script>

</body>
</html>
